﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QianBuo.Lottery.Web.Areas.Manage.Models;
using Code.BLL;
using Code.Models;

namespace QianBuo.Lottery.Web.Areas.Manage.Controllers
{
    [Authorize(Roles = "Manager_Site_Authorization")]
    public class ManagerController : BaseController
    {
        public ActionResult Index()
        {
            var model = new ManagerModel();
            var AM = new AdminManage();
            var admins = AM.Select(s => s.Select(p => new ManagerItem
            {
                ID = p.ID,
                AddTime = p.RegistTime,
                LoginName = p.LoginName,
                State = (AdminState)p.State,
                RoleID = p.RoleID,
                LastLoginTime =p.LoginLog.Where(pp => pp.LoginResult == (short)LoginResult.Normal).OrderByDescending(pp => pp.LoginTime).Select(pp => pp.LoginTime).FirstOrDefault()
            }).ToArray());
            model.Manages = admins.Each(p => { p.RoleName = CacheManage.Roles[p.RoleID].Name; p.Inline = OnLineManagers.ContainsKey(p.ID); });
            model.Current = base.AdminID;
            return View(model);
        }

        public ActionResult Edit(Guid id)
        {
            var AM = new AdminManage();
            var a = AM.Select(s => s.FirstOrDefault(p => p.ID == id));
            if (a == null)
                return RedirectToAction("Index");

            var model = new EditModel
            {
                ID=id,
                LoginName=a.LoginName,
                State=(AdminState)a.State,
                RoleID=a.RoleID,
                RolesList=CacheManage.Roles.Select(p=>new SelectListItem{Selected=p.Value.ID==a.RoleID,Text=p.Value.Name,Value=p.Value.ID.ToString()})
            };

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(EditModel model)
        {
            if (ModelState.IsValid)
            { 
                var AM = new AdminManage();
                var ck = AM.CheckPwd(base.AdminID, model.CheckPwd);
                if (!ck)
                    ModelState.AddModelError("CheckPwd", "密码不正确");
                else if (model.ID == base.AdminID && model.State == AdminState.Locked)
                    ModelState.AddModelError("State", "您不能锁定自己");
                else
                {
                    int rs = 0;
                    try
                    {
                        rs = AM.Edit(model.ID, model.Password, model.RoleID, model.State);
                    }
                    catch { }
                    string msg = null;
                    if (rs == 1)
                    {
                        msg = "修改成功！";
                        var admin = OnLineManagers[model.ID];
                        if (admin != null)
                            admin.IsLoad = true;
                    }
                    else
                        msg = "修改失败！";
                    return Content("<script>alert('" + msg + "');location.href='" + Url.Action("Index") + "'</script>");
                }
            }
            model.RolesList = CacheManage.Roles.Select(p => new SelectListItem { Selected = model.RoleID == p.Key, Text = p.Value.Name, Value = p.Value.ID.ToString() });
            return View(model);
        }

        public ActionResult Add()
        {
            var model = new AddManagerModel();
            model.RolesList = CacheManage.Roles.Select(p => new SelectListItem {Text = p.Value.Name, Value = p.Value.ID.ToString() });
            return View(model);
        }

        [HttpPost]
        public ActionResult Add(AddManagerModel model)
        {
           if (ModelState.IsValid)
            {
                var AM = new AdminManage();
                int rs = AM.Add(model.LoginName, model.Password, model.RoleID,model.State);
                if (rs > 0)
                    return Content("<script>alert('添加成功！');location.href='" + Url.Action("Index") + "'</script>");
                else
                    ViewData["msg"] = "操作失败，请稍后再试！".AlertOffPage();
            }
            model.RolesList = CacheManage.Roles.Select(p => new SelectListItem { Selected = model.RoleID == p.Key, Text = p.Value.Name, Value = p.Value.ID.ToString() });
            return View(model);
        }

        public ActionResult EditState(Guid id, AdminState state)
        {
            var AM = new AdminManage();
            int rs = AM.EditState(id, state);
            if (rs > 0)
            {
                var admin = OnLineManagers[id];
                if (admin != null)
                    admin.IsLoad = true;
            }
            string msg = rs <0 ? "修改失败，请稍后再试！" : "修改成功！";
            if (Request.IsAjaxRequest())
            {
                return Json(new { rs, msg }, JsonRequestBehavior.AllowGet);
            }
            return Content(string.Format("<script>alert('{0}');location.href='{1}'</script>", msg, Request["returnurl"] ?? Url.Action("Index")));
        }
    }
}
